package cn.wsalix.cms.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.wsalix.admin.entity.SysMenu;
import cn.wsalix.admin.service.MenuService;
import cn.wsalix.biz.entity.Article;
import cn.wsalix.biz.entity.Category;
import cn.wsalix.biz.form.FreemarkerForm;
import cn.wsalix.biz.service.AdvertiseService;
import cn.wsalix.biz.service.ArticleService;
import cn.wsalix.biz.service.CategoryService;
import cn.wsalix.cms.form.BuildSiteForm;
import cn.wsalix.cms.service.SiteBuildService;
import cn.wsalix.config.AppConfig;
import cn.wsalix.freemarker.FreemarkerUtil;
import cn.wsalix.templet.entity.SitePage;
import cn.wsalix.templet.entity.SitePagePlace;
import cn.wsalix.templet.form.SitePagePlaceForm;
import cn.wsalix.templet.service.SiteInfoService;
import cn.wsalix.templet.service.SitePagePlaceService;
import cn.wsalix.templet.service.SitePageService;

@Service("siteBuildService")
public class SiteBuildServiceImpl implements SiteBuildService {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private SiteInfoService siteInfoService;
	@Autowired
	private SitePageService sitePageService;
	@Autowired
	private SitePagePlaceService sitePagePlaceService;

	@PostConstruct
	public void init() {
		logger.info("==========init");
		// addObserver(sitePageService);
		// addObserver(siteInfoService);
	}

	@PreDestroy
	public void destroy() {
		logger.info("==========destroy");
	}

	@Transactional
	@Override
	public boolean build(BuildSiteForm form) {
		List<SitePage> sitePags = null;
		if (form.isAllBuild()) {
			// siteInfoService.findById(form.getSiteId())
			sitePags = sitePageService.findBySiteId(form.getSiteId());
		} else {
			SitePagePlaceForm sForm = new SitePagePlaceForm();
			List<SitePagePlace> sitePagePlaces = sitePagePlaceService
					.findByForm(sForm);
			sitePags = coverToPage(sitePagePlaces);
		}
		for (SitePage sitePage : sitePags) {
			buildOutFile(sitePage);
		}

		// setChanged();
		// notifyObservers(form);
		return false;
	}

	@Autowired
	private AppConfig appConfig;
	@Autowired
	private FreemarkerUtil freemarkerUtil;

	private String buildOutFile(SitePage sitePage) {
		FreemarkerForm form = new FreemarkerForm();
		form.setTemplateDir(appConfig.getTempleDir() + sitePage.getTempFile());
		try {
			File outFile = getOutFile(sitePage); // = new
													// File(appConfig.getHtmlOutPath(),
													// "order_"
			// + order.getId() + ".html");

			if (!outFile.exists()) {
				outFile.createNewFile();
			}
			Writer out = new OutputStreamWriter(new FileOutputStream(outFile),
					"GBK");
			Map<String, Object> resMap = getOutMap(sitePage);// new
																// HashMap<String,
																// Object>();
			// resMap.put("order", order);
			form.setParaMap(resMap);
			form.setTemplateFile("tuan_info.ftl");
			form.setOut(out);
			freemarkerUtil.buildFile(form);
			return "";
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Autowired
	private ArticleService articleService;
	@Autowired
	private AdvertiseService advertiseService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private MenuService menuService;
	private Map<String, Object> getOutMap(SitePage sitePage) {
		List<SitePagePlace> sitePagePlaces = sitePagePlaceService
				.findByPageId(sitePage.getId());
		for (SitePagePlace sitePagePlace : sitePagePlaces) {
			Map<String, Object> resMap = new HashMap<String, Object>();
			switch (sitePagePlace.getDataType()) {
			case AD_ONE:
				List<Article> adOne = articleService
						.findByCatoryId(sitePagePlace.getFkId());
				resMap.put(sitePagePlace.getPlaceCode(), adOne);
				break;
			case ARTICLE_GROUP:
				List<Article> articles = articleService
						.findByCatoryId(sitePagePlace.getFkId());
				resMap.put(sitePagePlace.getPlaceCode(), articles);
				break;
			case ARTICLE_ONE:
				Article article = articleService.findById(sitePagePlace
						.getFkId());
				resMap.put(sitePagePlace.getPlaceCode(), article);
				break;
			case CAT_GROUP:
				List<Category> cats = categoryService
						.findSubsById(sitePagePlace.getFkId());
				resMap.put(sitePagePlace.getPlaceCode(), cats);
				break;
			case CAT_ONE:
				Category cat = categoryService.findById(sitePagePlace.getFkId());
				resMap.put(sitePagePlace.getPlaceCode(), cat);
				break;
			case MENU_GROUP:
				List<SysMenu> menus = menuService
						.findSubsById(sitePagePlace.getFkId());
				resMap.put(sitePagePlace.getPlaceCode(), menus);
				break;
			case MENU_ONE:
				SysMenu menu = menuService
						.findById(sitePagePlace.getFkId());
				resMap.put(sitePagePlace.getPlaceCode(), menu);
				break;
			default:
				break;

			}
		}
		return null;
	}

	private File getOutFile(SitePage sitePage) {
		File outDir = new File(appConfig.getSaveFilePath()
				+ sitePage.getSiteInfo().getWebHostPath());
		if (!outDir.exists()) {
			outDir.mkdirs();
		}
		File outFile = new File(outDir, sitePage.getOutFile());
		return outFile;
	}

	private List<SitePage> coverToPage(List<SitePagePlace> sitePagePlaces) {
		// TODO Auto-generated method stub
		return null;
	}

}
